package cn.edu.baiyunu.myapplication.data.repository

import cn.edu.baiyunu.myapplication.data.TestDataGenerator
import cn.edu.baiyunu.myapplication.data.dao.TransactionDao
import cn.edu.baiyunu.myapplication.data.model.MonthlySummary
import cn.edu.baiyunu.myapplication.data.model.Transaction
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import javax.inject.Inject
import javax.inject.Singleton

/**
 * TransactionRepository接口的实现类
 */
@Singleton
class TransactionRepositoryImpl @Inject constructor(
    private val transactionDao: TransactionDao,
    private val categoryRepository: CategoryRepository
) : TransactionRepository {
    
    override fun getAllTransactions(): Flow<List<Transaction>> {
        return transactionDao.getAllTransactions()
    }
    
    override fun getTransactionById(id: String): Flow<Transaction?> {
        // 由于DAO的getTransactionById是suspend函数而不是Flow，
        // 我们需要使用map或者其他操作符转换获取的数据
        return getAllTransactions().map { transactions ->
            transactions.find { it.id == id }
        }
    }
    
    override fun getTransactionsByMonth(year: Int, month: Int): Flow<List<Transaction>> {
        val calendar = Calendar.getInstance()
        calendar.set(year, month - 1, 1, 0, 0, 0) // 月份从0开始，所以减1
        calendar.set(Calendar.MILLISECOND, 0)
        
        val startDate = calendar.timeInMillis
        
        // 设置到下个月的第一天
        calendar.add(Calendar.MONTH, 1)
        val endDate = calendar.timeInMillis - 1 // 减1毫秒，表示当月最后一毫秒
        
        return transactionDao.getTransactionsByDateRange(startDate, endDate)
    }
    
    override fun getRecentTransactions(limit: Int): Flow<List<Transaction>> {
        return transactionDao.getRecentTransactions(limit)
    }
    
    override suspend fun addTransaction(transaction: Transaction) {
        transactionDao.insertTransaction(transaction)
    }
    
    override suspend fun updateTransaction(transaction: Transaction) {
        transactionDao.updateTransaction(transaction)
    }
    
    override suspend fun deleteTransaction(id: String) {
        transactionDao.deleteTransactionById(id)
    }
    
    override fun getMonthlySummary(year: Int, month: Int): Flow<MonthlySummary> {
        val yearMonthFormat = SimpleDateFormat("yyyy-MM", Locale.getDefault())
        val calendar = Calendar.getInstance()
        calendar.set(year, month - 1, 1)
        val yearMonth = yearMonthFormat.format(calendar.time)
        
        val incomeFlow = transactionDao.getTotalIncomeByYearMonth(yearMonth)
        val expenseFlow = transactionDao.getTotalExpenseByYearMonth(yearMonth)
        
        return combine(incomeFlow, expenseFlow) { income, expense ->
            MonthlySummary(
                yearMonth = yearMonth,
                totalIncome = income,
                totalExpense = expense
            )
        }
    }
    
    /**
     * 初始化示例交易数据
     */
    override suspend fun initSampleData() {
        // 检查是否已有交易数据
        val transactions = transactionDao.getAllTransactions().first()
        if (transactions.isNotEmpty()) {
            return // 已有数据，不需要初始化
        }
        
        // 获取所有分类
        val expenseCategories = categoryRepository.getExpenseCategories().first()
        val incomeCategories = categoryRepository.getIncomeCategories().first()
        
        // 生成示例交易数据
        val sampleTransactions = TestDataGenerator.generateSampleTransactions(
            expenseCategories = expenseCategories,
            incomeCategories = incomeCategories
        )
        
        // 批量插入示例交易数据
        sampleTransactions.forEach { transaction ->
            transactionDao.insertTransaction(transaction)
        }
    }
} 